#!/bin/sh
# user_add.sh username passwd

set -e

help()
{
	echo "Usage: $0 username passwd"
}
add_user()
{
	if id -u ${USER} >/dev/null 2>&1
	then
		echo "${USER} exists"
		exit
	else
		useradd -g openvpn -s /usr/bin/false ${USER}
		echo ${USER}:${PASS} | chpasswd
		google-authenticator -t -d -r3 -R30 -W -f -l "openvpn server" -s /etc/openvpn/auth/${USER}
		echo "${USER} is created"
	fi
}	

new_config()
{
	# Generates the custom client.ovpn
	{
	cat /etc/openvpn/server/client-common.txt
	echo "reneg-sec 0"
    	echo "auth-nocache"
    	echo "auth-user-pass"
    	echo "static-challenge \"MFA OTP\" 1"
	echo "<ca>"
	cat /etc/openvpn/server/easy-rsa/pki/ca.crt
	echo "</ca>"
	echo "<cert>"
	sed -ne '/BEGIN CERTIFICATE/,$ p' /etc/openvpn/server/easy-rsa/pki/issued/client.crt
	echo "</cert>"
	echo "<key>"
	cat /etc/openvpn/server/easy-rsa/pki/private/client.key
	echo "</key>"
	echo "<tls-crypt>"
	sed -ne '/BEGIN OpenVPN Static key/,$ p' /etc/openvpn/server/tc.key
	echo "</tls-crypt>"
	} > ~/"${USER}".ovpn
}

if [ $# -lt 2 ]
then
	help
	exit
fi
USER=$1
PASS=$2
add_user
new_config

